package nuc.widget;

import java.util.ArrayList;
import java.util.List;

import nuc.SQLoperation.Constant;
import nuc.SQLoperation.SQLiteOperationHelper;
import nuc.wy.CreateNote;
import nuc.wy.NoteContent;
import nuc.wy.R;
import nuc.wy.SimpleNote;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.widget.RemoteViews;

public class WidgetActivity extends AppWidgetProvider{

	public final String NEXTACTION = "nuc.widget.WidgetActivity.NEXT";
	public final String PREACTION = "nuc.widget.WidgetActivity.PREV";
	public static List<SimpleNote> notes;
	public static int position = 0;
	SQLiteOperationHelper DBHelper;
	
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		// TODO Auto-generated method stub
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		
		update(context);
		
	}
	
	public void update(Context context){
		fetchMessages(context);
		/*position = 0;*/
		refreshView(context,NEXTACTION);
	}
	
	private Cursor getDb(Context context){
		DBHelper = new SQLiteOperationHelper(context, Constant.DB_NAME, null, 1);
		Cursor cursor = DBHelper.query("_lastdate desc");
		return cursor;
	}
	
	private void fetchMessages(Context context){
		if(notes == null){
			notes = new ArrayList<SimpleNote>();
		}
		else{
			notes.clear();
		}
		Cursor c = getDb(context);
		if(c != null){
			if(c.moveToFirst()){
				do{
					SimpleNote note = Parse.parseCursor(c);
					notes.add(note);
				}while(c.moveToNext());
			}
			else{
				ComponentName noteWidget = new ComponentName(context,
						WidgetActivity.class);
				AppWidgetManager manager = AppWidgetManager.getInstance(context);
				manager.updateAppWidget(noteWidget, buildUpdate(context));
			}
		}
		c.close();
		DBHelper.close();
	}

	private void refreshView(Context context,String action){
		// 某些情况下，notes会为null
		if (notes == null) {
			fetchMessages(context);
		}
		// 防止引发IndexOutOfBoundsException
		if (notes.size() != 0) {
			if (action.equals(NEXTACTION)) {
				--position;
			} else if (action.equals(PREACTION)) {
				++position;
			}
			if (position >= notes.size() || position < 0) {
				position = 0;
			}
			ComponentName noteWidget = new ComponentName(context,
					WidgetActivity.class);
			AppWidgetManager manager = AppWidgetManager.getInstance(context);
			manager.updateAppWidget(noteWidget, buildUpdate(context));
		}
	}
	
	public RemoteViews buildUpdate(Context context){
		RemoteViews updateViews = new RemoteViews(context.getPackageName(),R.layout.widgetlayout);
		
		if(notes.size() != 0){
			SimpleNote n = notes.get(position);
			updateViews.setTextViewText(R.id.widgetTextView, n.content);
			
			Intent inext = new Intent(context, WidgetActivity.class);
			inext.setAction(NEXTACTION);
			PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext,
					PendingIntent.FLAG_UPDATE_CURRENT);
			updateViews.setOnClickPendingIntent(R.id.btn_next, pinext);
			
			Intent ipre = new Intent(context, WidgetActivity.class);
			ipre.setAction(PREACTION);
			PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre,
					PendingIntent.FLAG_UPDATE_CURRENT);
			updateViews.setOnClickPendingIntent(R.id.btn_pre, pipre);
			
			Intent content = new Intent(context,NoteContent.class);
			content.putExtra("note", n);
			PendingIntent picontent = PendingIntent.getActivity(context, 0, content,
					PendingIntent.FLAG_UPDATE_CURRENT);
			updateViews.setOnClickPendingIntent(R.id.widgetTextView, picontent);
		}
		else {
			updateViews.setTextViewText(R.id.widgetTextView, "");
			
			Intent create = new Intent(context,CreateNote.class);
			PendingIntent picreate = PendingIntent.getActivity(context, 0, create, 
					PendingIntent.FLAG_UPDATE_CURRENT);
			updateViews.setOnClickPendingIntent(R.id.widgetTextView, picreate);
		}
		return updateViews;
	}

	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		String action = intent.getAction();

		if (NEXTACTION.equals(action) || PREACTION.equals(action)) {
			refreshView(context, intent.getAction());
			//System.out.println("!!!OnReceive");
		} 
		else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
			update(context);
		}
		
	    super.onReceive(context, intent);
	}
	
	
}
